package edu.fzu.shop.service.Impl;

import java.util.List;

import edu.fzu.shop.bean.CategoryBean;
import edu.fzu.shop.dao.CategoryDao;
import edu.fzu.shop.dao.Impl.CategoryDaoJDBCImpl;
import edu.fzu.shop.service.CategoryService;

public class CategoryServiceImpl implements CategoryService {

	public CategoryBean getCategoryById(Integer ctgId) {
		CategoryDao categoryDao = new CategoryDaoJDBCImpl();
		return categoryDao.getCategoryById(ctgId);
	}

	public List<CategoryBean> loadAll() {
		CategoryDao categoryDao = new CategoryDaoJDBCImpl();
		
		return categoryDao.loadAll();
	}

	public void remove(Integer ctgId) {
		CategoryDao categoryDao = new CategoryDaoJDBCImpl();
		try{
			CategoryBean  parentCtg=categoryDao.getCategoryById(categoryDao.getCategoryById(ctgId).getCtgParent());
			parentCtg.getCtgChildsList().remove(categoryDao.getCategoryById(ctgId));
			
			categoryDao.delete(ctgId);
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void save(CategoryBean categoryBean) {
		CategoryDao categoryDao = new CategoryDaoJDBCImpl();
		
		try{
			categoryDao.add(categoryBean);
			CategoryBean  parentCtg=categoryDao.getCategoryById(categoryBean.getCtgParent());
			parentCtg.getCtgChildsList().add(categoryBean);
			
			
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	public void update(CategoryBean categoryBean) {
		CategoryDao categoryDao = new CategoryDaoJDBCImpl();
		
			
		
		try{
			
			
			CategoryBean ctg=categoryDao.getCategoryById(categoryBean.getCtgId());
			if(ctg.getCtgParent()!=categoryBean.getCtgParent()){
				CategoryBean  newParentCtg=categoryDao.getCategoryById(categoryBean.getCtgParent());
				newParentCtg.getCtgChildsList().add(categoryBean);
				CategoryBean  oldParentCtg=categoryDao.getCategoryById(ctg.getCtgParent());
				oldParentCtg.getCtgChildsList().remove(categoryBean);
				
				categoryDao.update(categoryBean);
			}
			
		}catch(Exception e){
			e.printStackTrace();
			
		}

	}

}
